package com.hxgis.web.controller;


import com.hxgis.common.dto.RainInfoAnaStationDTO;
import com.hxgis.common.enums.DataColorFigEnum;
import com.hxgis.common.enums.SplashColorEnum;
import com.hxgis.common.service.RainAnalysisService;
import com.hxgis.common.service.graph.RainStormGraph;
import com.hxgis.common.utils.DownFileUtil;
import com.hxgis.common.utils.TimeUtil;
import com.hxgis.common.vo.RainInfoAnalysisVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.hxgis.common.utils.TimeUtil.FORMATOR_YMD;
import static com.hxgis.common.utils.TimeUtil.ZN_FORMATOR_YMD;

/**
 * 色斑图 和 下载 接口
 */
@RestController
@RequestMapping("splash")
@Slf4j
@Api(tags = "SplashController")
public class SplashController {

    @Autowired
    private RainAnalysisService rainAnalysisService;


    @Autowired
    private RainStormGraph rainStormGraph;

    @Value("${save.colorFigPath}")
    private String colorFigPath;


    /**
     * 情报分析降水量色斑图接口
     * @param startTime
     * @param endTime
     * @param leftTime
     * @param rightTime
     * @param flag 20 08
     * @param splashColorType QH_PRE：累计和30平均  QH_PRE_ANOMALY：距平百分率
     * @param sign now  max  min avg
     * @param isColreFig true:色斑下载 flase：站点图下载
     */
    @ApiOperation(value="情报分析降雨量色斑图接口", notes="色斑图 splashColorType：QH_PRE：累计和30平均   QH_PRE_ANOMALY：距平百分率，  sign：values  maxValues  minValues avg30  historyAvgRate  maxHistoryAvgRate  minHistoryAvgRate")
    @GetMapping("/intelligence/geoJson")
    public String downIntelligence(@RequestParam(value = "startTime",required = false) String startTime,
                                     @RequestParam(value = "endTime",required = false) String endTime,
                                     @RequestParam(value = "leftTime",required = false) String leftTime,
                                     @RequestParam(value = "rightTime",required = false) String rightTime,
                                     @RequestParam(value = "flag",required = false) String flag,
                                     @RequestParam(value = "sign",required = false) String sign,
                                     @RequestParam(value = "splashColorType",required = false) String splashColorType,
                                        @RequestParam(value = "isColreFig",required = false) boolean isColreFig,
                                        @RequestParam(value = "downFlag",required = false) Integer downFlag,
                                     HttpServletResponse response){
        RainInfoAnalysisVO rainInfoAnalysisVO  = (RainInfoAnalysisVO) rainAnalysisService.intelligence(startTime, endTime, leftTime, rightTime, flag, null).getData();
        //单位
        String unit = null;
        if (Objects.equals(splashColorType,SplashColorEnum.QH_PRE_DAYDISTANCE.getFlag())){
            unit = "日";
        }else  if (Objects.equals(splashColorType,SplashColorEnum.QH_PRE_ANOMALY.getFlag())){
            unit = "%";
        }else {
            unit = "mm";
        }
        //准备数据
        List<Double> values = new ArrayList<>();
        List<RainInfoAnaStationDTO> singStationInfos = rainInfoAnalysisVO.getSingStationInfos();

        if (Objects.equals(splashColorType, SplashColorEnum.QH_PRE.getFlag())){
            if (Objects.equals(sign, DataColorFigEnum.VALUES.getType())){
                singStationInfos = singStationInfos.stream().filter((p) -> (p.getValues() < 999999)).collect(Collectors.toList());
                values  = singStationInfos.stream().map(u -> u.getValues()).collect(Collectors.toList());
            }else if (Objects.equals(sign, DataColorFigEnum.MAXVALUES.getType())){
                singStationInfos = singStationInfos.stream().filter((p) -> (p.getMaxValues() < 999999)).collect(Collectors.toList());
                values  = singStationInfos.stream().map(u -> u.getMaxValues()).collect(Collectors.toList());
            } else if (Objects.equals(sign, DataColorFigEnum.MINVALUES.getType())){
                singStationInfos = singStationInfos.stream().filter((p) -> (p.getMinValues() < 999999)).collect(Collectors.toList());
                values  = singStationInfos.stream().map(u -> u.getMinValues()).collect(Collectors.toList());
            }else if (Objects.equals(sign, DataColorFigEnum.AVG.getType())){
                singStationInfos = singStationInfos.stream().filter((p) -> (p.getAvg30() < 999999)).collect(Collectors.toList());
                values  = singStationInfos.stream().map(u -> u.getAvg30()).collect(Collectors.toList());
            }
        }else{
            if (Objects.equals(sign, DataColorFigEnum.HISTORYAVGRATE.getType())){
                singStationInfos = singStationInfos.stream().filter((p) -> (p.getHistoryAvgRate() < 999999)).collect(Collectors.toList());
                values  = singStationInfos.stream().map(u -> u.getHistoryAvgRate()).collect(Collectors.toList());
            }else if (Objects.equals(sign, DataColorFigEnum.MAXHISTORYAVGRATE.getType())){
                singStationInfos = singStationInfos.stream().filter((p) -> (p.getMaxHistoryAvgRate() < 999999)).collect(Collectors.toList());
                values  = singStationInfos.stream().map(u -> u.getMaxHistoryAvgRate()).collect(Collectors.toList());
            } else if (Objects.equals(sign, DataColorFigEnum.MINHISTORYAVGRATE.getType())){
                singStationInfos = singStationInfos.stream().filter((p) -> (p.getMinHistoryAvgRate() < 999999)).collect(Collectors.toList());
                values  = singStationInfos.stream().map(u -> u.getMinHistoryAvgRate()).collect(Collectors.toList());
            }
        }
        //经纬度
        List<Double> latLists = singStationInfos.stream().map(u -> u.getLat()).collect(Collectors.toList());
        List<Double> lonLists = singStationInfos.stream().map(u -> u.getLon()).collect(Collectors.toList());
        Long st = System.currentTimeMillis();
        //不裁剪
        if (Objects.isNull(downFlag)){
            String geoJson = rainStormGraph.getGeoJson(splashColorType, values, latLists, lonLists, 999999d, unit);
            log.info("情报分析降雨量色斑图转换用时：{}",System.currentTimeMillis()-st);
//            log.info(geoJson);
            return geoJson;
        }else{
            //下载接口
            String url = null;
            try {
                String firstTitle = null;
                String secondTitle = null;

                String urlName = "全国累计降水量(" + flag + "-" + flag +")" +
                        SplashColorEnum.getSplashColorEnum(splashColorType).getMessage() + DataColorFigEnum.getSplashColorEnum(sign).getMessage();

                if (Objects.equals(startTime,endTime)){
                    secondTitle = TimeUtil.changeStyle(startTime,FORMATOR_YMD,ZN_FORMATOR_YMD);
                }else{
                    secondTitle = TimeUtil.changeStyle(startTime,FORMATOR_YMD,ZN_FORMATOR_YMD) + "到"+ TimeUtil.changeStyle(endTime,FORMATOR_YMD,ZN_FORMATOR_YMD);
                }
                firstTitle = urlName + "[" + unit + "]";
                String fileName = null;
                if (isColreFig){
                    fileName = colorFigPath + File.separator + urlName + secondTitle + "色斑图" + ".png";
                }else{
                    fileName = colorFigPath + File.separator + urlName + secondTitle + "站点图" + ".png";
                }
                url = rainStormGraph.genColorMap(fileName, firstTitle, secondTitle, isColreFig,  unit, 999999d, SplashColorEnum.getSplashColorEnum(splashColorType).getFlag(),
                        values, latLists, lonLists);
                log.info("情报分析降雨量色斑图下载转换用时：{}",System.currentTimeMillis()-st);
            } catch (Exception e) {
                e.printStackTrace();
            }
            File file = new File(url);
            if (file.exists()) {
                DownFileUtil.printFile(file, response);
                file.delete();
            }
        }
        return null;
    }



    //情报分析 暴雨日  QH_PRE_DAYS  QH_PRE_DAYDISTANCE
    /**
     * 情报分析降雨日统计接口
     * @param startTime
     * @param endTime
     * @param leftTime 数据范围开始时间
     * @param rightTime 数据范围结束时间
     * @param type
     * @param flag20 gt,xx,lt,xx  gt,1,lt,xx
     * @param flag08 gt,xx,lt,xx
     * @return
     */
    @ApiOperation(value="情报分析降雨日统计接口", notes="splashColorType：QH_PRE_DAYS：累计值   QH_PRE_DAYDISTANCE：历史距平  sign：values  maxValues  minValues avg30  historyAvgRate  maxHistoryAvgRate  minHistoryAvgRate，，  startTime：开始时间，endTime：结束时间，查看范围开始时间：leftTime，" +
            "查看范围结束时间：rightTime,type:无雨日，雨日，暴雨日，大暴雨日，自定义，只有当type不为自定义的时候flag20 和 flag08为空， flag20：gt,xx,lt,xx  gt,1,lt,xx，flag08：gt,xx,lt,xx  gt,1,lt,xx，stationNo：可以为空，如果查询所有的信息就不传")
    @GetMapping("/intelligence/day/geoJson")
    public String intelligenceByRainDay(@RequestParam(value = "startTime",required = false) String startTime,
                                          @RequestParam(value = "endTime",required = false) String endTime,
                                          @RequestParam(value = "leftTime",required = false) String leftTime,
                                          @RequestParam(value = "rightTime",required = false) String rightTime,
                                          @RequestParam(value = "type",required = false) String type,
                                          @RequestParam(value = "flag20",required = false) String flag20,
                                          @RequestParam(value = "flag08",required = false) String flag08,
                                          @RequestParam(value = "sign",required = false) String sign,
                                          @RequestParam(value = "splashColorType",required = false) String splashColorType,
                                        @RequestParam(value = "isColreFig",required = false) boolean isColreFig,
                                        @RequestParam(value = "downFlag",required = false) Integer downFlag,
                                        HttpServletResponse response
    ){
        RainInfoAnalysisVO rainInfoAnalysisVO  = (RainInfoAnalysisVO) rainAnalysisService.intelligenceByRainDay(startTime, endTime, leftTime, rightTime, type, flag20, flag08, null).getData();
        //单位
        String unit = "日";
        //准备数据
        List<Double> values = new ArrayList<>();
        List<RainInfoAnaStationDTO> singStationInfos = rainInfoAnalysisVO.getSingStationInfos();

        if (Objects.equals(splashColorType, SplashColorEnum.QH_PRE_DAYS.getFlag())){
            if (Objects.equals(sign, DataColorFigEnum.VALUES.getType())){
                singStationInfos = singStationInfos.stream().filter((p) -> (p.getValues() < 999999)).collect(Collectors.toList());
                values  = singStationInfos.stream().map(u -> u.getValues()).collect(Collectors.toList());
            } else if (Objects.equals(sign, DataColorFigEnum.AVG.getType())){
                singStationInfos = singStationInfos.stream().filter((p) -> (p.getAvg30() < 999999)).collect(Collectors.toList());
                values  = singStationInfos.stream().map(u -> u.getAvg30()).collect(Collectors.toList());
            } else if (Objects.equals(sign, DataColorFigEnum.MINVALUES.getType())){
                singStationInfos = singStationInfos.stream().filter((p) -> (p.getMinValues() < 999999)).collect(Collectors.toList());
                values  = singStationInfos.stream().map(u -> u.getMinValues()).collect(Collectors.toList());
            } else if (Objects.equals(sign, DataColorFigEnum.MAXVALUES.getType())){
                singStationInfos = singStationInfos.stream().filter((p) -> (p.getMaxValues() < 999999)).collect(Collectors.toList());
                values  = singStationInfos.stream().map(u -> u.getMaxValues()).collect(Collectors.toList());
            }
        }else{
            if (Objects.equals(sign, DataColorFigEnum.HISTORYAVGRATE.getType())){
                singStationInfos = singStationInfos.stream().filter((p) -> (p.getHistoryAvgRate() < 999999)).collect(Collectors.toList());
                values  = singStationInfos.stream().map(u -> u.getHistoryAvgRate()).collect(Collectors.toList());
            } else if (Objects.equals(sign, DataColorFigEnum.MINHISTORYAVGRATE.getType())){
                singStationInfos = singStationInfos.stream().filter((p) -> (p.getMinHistoryAvgRate() < 999999)).collect(Collectors.toList());
                values  = singStationInfos.stream().map(u -> u.getMinHistoryAvgRate()).collect(Collectors.toList());
            } else if (Objects.equals(sign, DataColorFigEnum.MAXHISTORYAVGRATE.getType())){
                singStationInfos = singStationInfos.stream().filter((p) -> (p.getMaxHistoryAvgRate() < 999999)).collect(Collectors.toList());
                values  = singStationInfos.stream().map(u -> u.getMaxHistoryAvgRate()).collect(Collectors.toList());
            }
        }
        //经纬度
        List<Double> latLists = singStationInfos.stream().map(u -> u.getLat()).collect(Collectors.toList());
        List<Double> lonLists = singStationInfos.stream().map(u -> u.getLon()).collect(Collectors.toList());
        if (Objects.isNull(downFlag)){
            Long st = System.currentTimeMillis();
            //不裁剪
            String geoJson = rainStormGraph.getGeoJson(splashColorType, values, latLists, lonLists, 999999d, unit);
            log.info("情报分析降雨日色斑图转换用时：{}",System.currentTimeMillis()-st);
            return geoJson;
        }else{
            String url = null;
            try {
                String firstTitle = null;
                String secondTitle = null;

                String urlName = "全国累计" + type +
                        SplashColorEnum.getSplashColorEnum(splashColorType).getMessage() + DataColorFigEnum.getSplashColorEnum(sign).getMessage();

                if (Objects.equals(startTime,endTime)){
                    secondTitle = TimeUtil.changeStyle(startTime,FORMATOR_YMD,ZN_FORMATOR_YMD);
                }else{
                    secondTitle = TimeUtil.changeStyle(startTime,FORMATOR_YMD,ZN_FORMATOR_YMD) + "到"+ TimeUtil.changeStyle(endTime,FORMATOR_YMD,ZN_FORMATOR_YMD);
                }
                firstTitle = urlName + "[" + unit + "]";
                String fileName = null;
                if (isColreFig){
                    fileName = colorFigPath + File.separator + urlName + secondTitle + "色斑图" + ".png";
                }else{
                    fileName = colorFigPath + File.separator + urlName + secondTitle + "站点图" + ".png";
                }
                url = rainStormGraph.genColorMap(fileName, firstTitle, secondTitle, isColreFig,  unit, 999999d, SplashColorEnum.getSplashColorEnum(splashColorType).getFlag(),
                        values, latLists, lonLists);
            } catch (Exception e) {
                e.printStackTrace();
            }
            File file = new File(url);
            if (file.exists()) {
                DownFileUtil.printFile(file, response);
                file.delete();
            }
            return null;
        }

    }






}
